
#import "NSObject+LanBNotifyMessage.h"
#import <LanBKit/LanBSwizzle.h>

@interface NSObject ()
@property (nonatomic , strong) NSMutableArray *aryObservers;
@end

@implementation NSObject (LanBNotifyMessage)

+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        SEL originalSelector = NSSelectorFromString(@"dealloc");
        SEL swizzledSelector = @selector(lanb_notifyMessage_dealloc);
        lanB_swizzle_instanceMethod(originalSelector, swizzledSelector, self);
    });
}

- (void)lanb_notifyMessage_dealloc
{
    if (self.aryObservers) {
        [self.aryObservers enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [[NSNotificationCenter defaultCenter] removeObserver:obj];
        }];
        [self.aryObservers removeAllObjects];
        self.aryObservers = nil;
    }
    [self lanb_notifyMessage_dealloc];
}

#pragma mark - apis
- (void)lanB_postNotificationName:(NSString *)aName object:(id)anObject userInfo:(NSDictionary *)aUserInfo
{
    [[NSNotificationCenter defaultCenter] postNotificationName:aName object:anObject userInfo:aUserInfo];
}

- (id<NSObject>)lanB_addObserverForName:(NSString *)name block:(void (^)(NSNotification * _Nullable))block
{
    if (!self.aryObservers) {
        self.aryObservers = [NSMutableArray new];
    }
    id observe = [[NSNotificationCenter defaultCenter] addObserverForName:name object:nil queue:[NSOperationQueue mainQueue] usingBlock:block];
    [self.aryObservers addObject:observe];
    return observe;
}

#pragma mark - seeter getter
static void *aryObservers_key = &aryObservers_key;
- (void)setAryObservers:(NSMutableArray *)aryObservers
{
    objc_setAssociatedObject(self, &aryObservers_key, aryObservers, OBJC_ASSOCIATION_RETAIN);
}

- (NSMutableArray *)aryObservers
{
    return objc_getAssociatedObject(self, &aryObservers_key);
}

@end
